<script setup lang="ts">
import { defineEmits, defineProps, onMounted, ref, watch } from 'vue'

const props = defineProps<{
  width?: number | string
  height?: number | string
}>()

const emit = defineEmits<{
  (e: 'ready', ctx: CanvasRenderingContext2D | null): void
}>()

const canvasRef = ref<HTMLCanvasElement | null>(null)

const width = ref(props.width ?? 300)
const height = ref(props.height ?? 150)

watch(
  () => props.width,
  (val) => {
    width.value = val ?? 300
  },
)
watch(
  () => props.height,
  (val) => {
    height.value = val ?? 150
  },
)

onMounted(() => {
  if (canvasRef.value) {
    const ctx = canvasRef.value.getContext('2d')
    emit('ready', ctx)
  }
})
</script>

<template>
  <canvas ref="canvasRef" class="canvas" :width="width" :height="height" :class="$attrs.class">
    换个浏览器，求求了
  </canvas>
</template>

<style scoped lang="scss">
.canvas{
  border: 1px solid #000;
}
</style>
